import storage from '@/utils/storage'
import {
	login,
	logout,
	getInfo
} from "@/api/modules/login.api.js"
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'
import config from '@/config.js'

const user = {
	state: {
		token: getToken(),
		userInfo: uni.getStorageSync('userInfo'),
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			setToken(token)
		},
		SET_USERINFO: (state, data) => {
			state.userInfo = data
			storage.set('userInfo', data)
		},
		update(state, [key, value]) {
			state[key] = value;
			uni.setStorageSync(key, value)
		},
	},
	actions: {
		// 登录
		Login({
			commit,
			dispatch
		}, userInfo) {
			return new Promise((resolve, reject) => {
				login(userInfo.form)
					.then(res => {
						if (res.code == 200) {
							commit('SET_TOKEN', res.data.token)
							commit('update', ['userId', res.data.userId])
							dispatch('GetInfo', userInfo.path)
						}
						resolve(res)
					})
					.catch(error => {
						reject(error)
					})
			})
		},
		// 获取用户信息
		GetInfo({
			commit,
			state
		}, path) {
			return new Promise((resolve, reject) => {
				getInfo(state.userId)
					.then(res => {
						if (res.code == 200) {
							let user = res.data
							let expireTime = new Date().getTime() + 15 * 24 * 60 * 60 * 1000
							user.avatar = config.imgUrl + user.avatar
							if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
								commit('update', ['roles', res.roles])
								commit('update', ['permissions', res.permissions])
							} else {
								commit('update', ['roles', 'ROLE_DEFAULT'])
							}
							commit('SET_USERINFO', user)
							storage.set('expireTime', expireTime)
							storage.set('proStatus', user.proStatus)
							uni.showToast({
								title: '登录成功',
								icon: 'none',
								success() {
									uni.router.to({
										path: path,
										params: user
									})
								}
							})
						}
						resolve(res)
					})
					.catch(error => {
						reject(error)
					})
			})
		},
		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout(state.token)
					.then(() => {
						// uni.clearStorageSync()
						removeToken()
						uni.removeStorageSync('userId', "");
						uni.removeStorageSync('userInfo', "");
						uni.removeStorageSync('identity', "");
						resolve()
					})
					.catch(error => {
						reject(error)
					})
			})
		},
	}
}
export default user